package com.xhwl.centiotdata.pollingtrigger.pedestrian;

import com.xhwl.centiotdata.handler.account.AccountFactory;
import com.xhwl.centiotdata.handler.account.AccountHandler;
import com.xhwl.centiotdata.handler.device.DeviceIntegrationFactory;
import com.xhwl.centiotdata.handler.device.DeviceIntegrationHandler;
import com.xhwl.centiotdata.handler.pedestrian.PedestrianIntegrationFactory;
import com.xhwl.centiotdata.handler.pedestrian.PedestrianIntegrationHandler;
import com.xhwl.centiotdata.pojo.dto.device.DeviceIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.enums.pedestrian.PedestrianMethodEnum;
import com.xhwl.centiotdata.pollingtrigger.ScheduleDispatcher;
import com.xhwl.centiotdata.service.integrateconfig.PedestrianIntegrationConfig;
import com.xhwl.centiotdata.utils.ThreadPoolUtils;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.enums.device.DeviceTypeEnum;
import com.xhwl.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/09/03/ 09:25
 */
@Slf4j
@Service
public class PedestrianDispatcher implements ScheduleDispatcher {

    @Autowired
    private PedestrianIntegrationConfig integrationConfig;

    @Override
    public void doTenSecondsTask() {
        // 人行获取出入记录
        Date date = new Date();
        ThreadPoolUtils.pedestrianExecutor.execute(() -> this.executePullPedestrianRecord(null,date));
    }

    @Override
    public void doTenMinutesTask() {
        // 人行获取门禁设备在离线状态
        ThreadPoolUtils.executor.execute(this::executePullPedestrianDeviceOnlineStatus);
        // 人行获取出入记录统计
        ThreadPoolUtils.baiLianSyncExecutor.execute(() -> this.executePullPedestrianRecordStatistics(null));

        // 金茂校园 人行获取昨日查验记录统计
        ThreadPoolUtils.executor.execute(this::executePullCheckData);
        // 金茂校园 人行获取昨日访客记录
        ThreadPoolUtils.executor.execute(() -> this.executePullVisitorData(null));
    }

    @Override
    public void doOneHourTask() {
        // 人行获取考勤打卡记录
        ThreadPoolUtils.executor.execute(() -> this.executePullClockRecord(null, null));
        // 定时拉取人行记录
        Date date = new Date();
        ThreadPoolUtils.pedestrianExecutor.execute(() -> this.executePullPedestrianClockRecord(date));
    }

    @Override
    public void doOneDayTask() {
        // 人行获取门禁设备
        ThreadPoolUtils.executor.execute(this::executePullPedestrianDevice);
        // 人行获取报警主机设备
        ThreadPoolUtils.executor.execute(this::executePullAlarmHostDevice);
        // 人行获取昨日出入记录统计
        ThreadPoolUtils.executor.execute(this::executePullPedestrianRecordStatisticsLastDay);
    }

    /**
     * 拉取提前多少天的人行数据
     *
     * @param intervalDays 比如 -2 ，2天前. null，当天
     * @param date
     */
    public void executePullPedestrianRecord(Integer intervalDays, Date date) {
        // 获取到需要执行拉取人行出入记录的项目及配置
        List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null).getOrDefault(PedestrianMethodEnum.RECORD.getId(), Collections.emptyList());
        integrationConfigDTOList.forEach(integrationConfigDTO -> {
            try {
                log.info("开始拉取：{}", integrationConfigDTO.getProductId());
                PedestrianIntegrationHandler handler = PedestrianIntegrationFactory.getInvokeStrategy(integrationConfigDTO.getProductId());
                if (handler == null) {
                    return;
                }
                // 如果未定义查询时间段,直接查15s前的时间
                if (integrationConfigDTO.getPullSecond()==null||integrationConfigDTO.getPullSecond()==0){
                    Integer beforeTime=15;
                    integrationConfigDTO.setPullSecond(beforeTime);
                }
                handler.pullRecord(integrationConfigDTO, intervalDays,date);
            } catch (Exception e) {
                log.error("[人行拉取报错日志]",e);
                e.printStackTrace();
            }
        });
    }

    /**
     * 定时拉取人行记录
     */
    public void executePullPedestrianClockRecord(Date date) {
        // 获取到需要执行拉取人行出入记录的项目及配置
        List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null).getOrDefault(PedestrianMethodEnum.RECORD.getId(), Collections.emptyList());
        integrationConfigDTOList.forEach(integrationConfigDTO -> {
            try {
                log.info("开始拉取：{}", integrationConfigDTO.getProductId());
                PedestrianIntegrationHandler handler = PedestrianIntegrationFactory.getInvokeStrategy(integrationConfigDTO.getProductId());
                if (handler == null) {
                    return;
                }
                handler.pullVisits(integrationConfigDTO, date);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void executePullClockRecord(Integer offSet, Integer limit) {
        // 获取到需要执行拉取员工考勤记录的项目及配置
        List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null).getOrDefault(PedestrianMethodEnum.CLOCK.getId(), Collections.emptyList());
        integrationConfigDTOList.stream().forEach(integrationConfigDTO -> {
            try {
                log.info("开始拉取：{}", integrationConfigDTO.getProductId());
                PedestrianIntegrationHandler handler = PedestrianIntegrationFactory.getInvokeStrategy(integrationConfigDTO.getProductId());
                if (handler == null) {
                    return;
                }
                handler.pullClockRecord(integrationConfigDTO, offSet, limit);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void executePullPedestrianRecordStatisticsLastDay() {
        // 获取到需要执行拉取人行出入记录的项目及配置
        List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null).getOrDefault(PedestrianMethodEnum.RECORD_STATISTICS_LAST_DAY.getId(), Collections.emptyList());
        integrationConfigDTOList.stream().forEach(integrationConfigDTO -> {
            try {
                log.info("开始拉取：{}", integrationConfigDTO.getProductId());
                PedestrianIntegrationHandler handler = PedestrianIntegrationFactory.getInvokeStrategy(integrationConfigDTO.getProductId());
                if (handler == null) {
                    return;
                }
                handler.pullRecordStatistics(integrationConfigDTO, -1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void executePullAlarmHostDevice() {
        // 获取到需要执行拉取人行设备的项目及配置
        List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null)
                .getOrDefault(PedestrianMethodEnum.DEVICE.getId(), Collections.emptyList());
        integrationConfigDTOList.forEach(item -> {
            try {
                DeviceIntegrationHandler handler = DeviceIntegrationFactory.getInvokeStrategy(item.getProductId());
                if (Objects.isNull(handler)) {
                    return;
                }
                DeviceIntegrationConfigDTO configDTO = new DeviceIntegrationConfigDTO();
                BeanUtils.copyProperties(item, configDTO);
                configDTO.setDeviceType(DeviceTypeEnum.ALARM_HOST_DEVICE.getCode());
                configDTO.setCategoryEnum(CategoryEnum.ALARM_HOST_SYSTEM);
                log.info("查询报警主机设备入参==>{}", configDTO);
                handler.pullAlarmHostDevice(configDTO);
            } catch (Exception ex) {
                log.error("拉取设备异常==>{}", ex.getMessage());
            }
        });
    }

    public void executePullPedestrianDevice() {
        // 获取到需要执行拉取人行设备的项目及配置
        List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null).getOrDefault(PedestrianMethodEnum.DEVICE.getId(), Collections.emptyList());
        log.info("获取的人行集成配置为:{}",integrationConfigDTOList);
        integrationConfigDTOList.stream().forEach(integrationConfigDTO -> {
            log.info("integrationConfigDTO{}",integrationConfigDTO);
            try {
                log.info("开始拉取设备：{}"+integrationConfigDTO.getProductId());
                DeviceIntegrationHandler handler = DeviceIntegrationFactory.getInvokeStrategy(integrationConfigDTO.getProductId());
                if (handler == null) {
                    return;
                }
                DeviceIntegrationConfigDTO configDTO = new DeviceIntegrationConfigDTO();
                BeanUtils.copyProperties(integrationConfigDTO, configDTO);
                configDTO.setOrgCode(integrationConfigDTO.getOrgIndexCode());
                configDTO.setDeviceType(1);
                configDTO.setCategoryEnum(CategoryEnum.DOOR);
                log.info("开始拉取设备参数：{}"+configDTO);
                handler.pullDevice(configDTO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    public void executeSyncStaffAuto() {
        List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null).getOrDefault(PedestrianMethodEnum.SYNC_USER.getId(), Collections.emptyList());
        integrationConfigDTOList.stream().forEach(integrationConfigDTO -> {
            try {
                AccountHandler handler = AccountFactory.getInvokeStrategy(integrationConfigDTO.getProductId());
                log.info("开始拉取：{}---{}", integrationConfigDTO.getProductId(),handler);
                if (handler == null) {
                    return;
                }
                handler.syncUserAuto(integrationConfigDTO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    public void executePullPedestrianDeviceOnlineStatus() {
        // 获取到需要执行拉取人行设备在离线状态的项目及配置
        List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null).getOrDefault(PedestrianMethodEnum.DEVICE_ONLINE_STATUS.getId(), Collections.emptyList());
        if (integrationConfigDTOList == null)
            return;
        integrationConfigDTOList.forEach(integrationConfigDTO -> {
            try {
                log.info("开始拉取：{}", integrationConfigDTO.getProductId());
                DeviceIntegrationHandler handler = DeviceIntegrationFactory.getInvokeStrategy(integrationConfigDTO.getProductId());
                if (handler == null) {
                    return;
                }
                DeviceIntegrationConfigDTO configDTO = new DeviceIntegrationConfigDTO();
                BeanUtils.copyProperties(integrationConfigDTO, configDTO);
                configDTO.setDeviceType(1);
                handler.pullDeviceOnlineStatus(configDTO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void executePullPedestrianRecordStatistics(Integer intervalDays) {
        // 获取到需要执行拉取人行出入记录统计的项目及配置
        List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null).getOrDefault(PedestrianMethodEnum.RECORD_STATISTICS.getId(), Collections.emptyList());
        integrationConfigDTOList.forEach(integrationConfigDTO -> {
            try {
                log.info("开始拉取：{}", integrationConfigDTO.getProductId());
                PedestrianIntegrationHandler handler = PedestrianIntegrationFactory.getInvokeStrategy(integrationConfigDTO.getProductId());
                if (handler == null) {
                    return;
                }
                handler.pullRecordStatistics(integrationConfigDTO, intervalDays);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

        public void executePullCheckData(){
            // 获取拉取数字哨兵记录的项目及配置
            List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null).getOrDefault(PedestrianMethodEnum.RECORD.getId(), Collections.emptyList());
            //log.info("内容为 {}",integrationConfigDTOList);
            integrationConfigDTOList.forEach(integrationConfigDTO -> {
                try {
                    PedestrianIntegrationHandler handler = PedestrianIntegrationFactory.getInvokeStrategy(integrationConfigDTO.getProductId());
                    if (handler == null) {
                        return;
                    }
                    handler.pullCheckData(integrationConfigDTO);
                } catch (Exception e) {
                    e.printStackTrace();
                }
        });
    }

    public void executePullVisitorData(Integer intervalDays){
        // 获取拉取数字哨兵记录的项目及配置
        List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null).getOrDefault(PedestrianMethodEnum.RECORD.getId(), Collections.emptyList());
        integrationConfigDTOList.forEach(integrationConfigDTO -> {
            try {
                PedestrianIntegrationHandler handler = PedestrianIntegrationFactory.getInvokeStrategy(integrationConfigDTO.getProductId());
                if (handler == null) {
                    return;
                }
                handler.pullVisitorData(intervalDays,integrationConfigDTO);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
